package com.sakura.oj.sandbox.utils;

import com.github.dockerjava.api.async.ResultCallback;
import com.github.dockerjava.api.model.Frame;
import com.github.dockerjava.api.model.StreamType;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

/**
 * Docker执行回调处理类
 * 处理Docker命令执行过程中的输出和错误，同时屏蔽管道关闭的异常
 */
@Slf4j
public class DockerExecuteCallback extends ResultCallback.Adapter<Frame> {
    
    private final StringBuilder stdout;
    private final StringBuilder stderr;
    
    /**
     * 构造函数
     * @param stdout 标准输出缓冲区
     * @param stderr 标准错误缓冲区
     */
    public DockerExecuteCallback(StringBuilder stdout, StringBuilder stderr) {
        this.stdout = stdout;
        this.stderr = stderr;
    }
    
    @Override
    public void onNext(Frame frame) {
        if (frame.getStreamType() == StreamType.STDOUT) {
            stdout.append(new String(frame.getPayload()));
        } else if (frame.getStreamType() == StreamType.STDERR) {
            stderr.append(new String(frame.getPayload()));
        }
        super.onNext(frame);
    }
    
    @Override
    public void onError(Throwable throwable) {
        // 屏蔽管道关闭相关的异常
        if (throwable instanceof IOException && 
            (throwable.getMessage().contains("管道已") || 
             throwable.getMessage().contains("pipe") || 
             throwable.getMessage().contains("Pipe") || 
             throwable.getMessage().contains("closed"))) {
            // 不做任何处理，屏蔽此异常
            return;
        }
        // 其他异常正常处理
        super.onError(throwable);
    }
} 